//
//  MujiDubDatabaseManager.m
//  testdemo
//
//  Created by yule on 2017/5/19.
//  Copyright © 2017年 yule. All rights reserved.
//

#import "MujiDubDatabaseManager.h"


@implementation MujiDubDatabaseManager

+ (instancetype)shareManager
{
    static MujiDubDatabaseManager *manager;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[MujiDubDatabaseManager alloc] init];
    });
    return manager;
}

- (instancetype)init
{
    if (self = [super init]) {
        NSString *libaryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
        
        NSString *filePath = [libaryPath stringByAppendingPathComponent:@"MujiDubCache"];
        NSError *outError = nil;

        NSFileManager *fileManager = [NSFileManager defaultManager];
        if (![fileManager fileExistsAtPath:filePath]) {
            
            if ([fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:&outError])
            {
                [self initSqliteWithPath:filePath];
            }
        }else {
            [self initSqliteWithPath:filePath];

        }
    }
    return self;
}
- (void)initSqliteWithPath:(NSString *)path
{
    NSString *databasePath = [path stringByAppendingPathComponent:kDatabaseFileName];

    
    _database = [FMDatabase databaseWithPath:databasePath];
    if ([_database open]) {
        
        
        NSString *createTableSql = @"create table if not exists MujiDubHistoryList(userId TEXT, dialogid TEXT,  dialoglineid TEXT, score TEXT, result TEXT, mindex TEXT)";
        
        if (![_database executeUpdate:createTableSql]) {
            [NSException raise:NSInternalInconsistencyException format:@"创表失败"];
        }
    }
    else {
        // 抛出一个异常，程序会挂掉（不一定非要这么做）
        [NSException raise:NSInternalInconsistencyException format:@"数据库打开失败"];
    }
}

- (void)insertResultModel:(MujiDubRecordModel *)model
{
    NSString *sql = @"insert into MujiDubHistoryList(userId, dialogid, dialoglineid, score, result, mindex) VALUES(?, ?, ?, ?, ?, ?)";
    
    
    if (![_database executeUpdate:sql, model.userId, model.dialogid, model.dialoglineid, model.score, model.result, model.mindex]) {
        //NSLog(@"数据插入失败");
    }
}
- (void)deleteResultModel:(MujiDubRecordModel *)model
{
    
    NSString *sql = @"delete from MujiDubHistoryList where userId=? and dialogid=? and dialoglineid=? and mindex=?";
    if (![_database executeUpdate:sql, model.userId, model.dialogid, model.dialoglineid, model.mindex]) {
        //NSLog(@"删除数据失败");
    }
    
}
- (void)updateResultModel:(MujiDubRecordModel *)model
{
    
    NSString *sql = @"update MujiDubHistoryList set userId=?, dialogid=?, dialoglineid=? where score=? and result=? and mindex=?";
    if (![_database executeUpdate:sql, model.userId, model.dialogid, model.dialoglineid, model.score, model.result, model.mindex]) {
        //NSLog(@"数据更新失败");
    }
}

- (NSArray *)queryAllHistoryModelWithUserId:(NSString *)userId
{
    NSString *sql = @"SELECT * FROM MujiDubHistoryList where userId=?";
    FMResultSet *rs = [_database executeQuery:sql, userId];
    
    NSMutableArray *resultArr = [[NSMutableArray alloc] init];
    while ([rs next]) {
        
        // 查询到一条记录，就应该新建一个Model来放数据
        MujiDubRecordModel *model = [[MujiDubRecordModel alloc] init];
        model.userId = [rs stringForColumn:@"userId"];
        model.dialogid = [rs stringForColumn:@"dialogid"];
        model.dialoglineid = [rs stringForColumn:@"dialoglineid"];
        model.score = [rs stringForColumn:@"score"];
        model.result= [rs stringForColumn:@"result"];
        model.mindex= [rs stringForColumn:@"mindex"];

        
        if (model.score.length == 0 || [model.score containsString:@"null"]) {
            model.score = @"";
        }
        if (model.result.length == 0 || [model.result containsString:@"null"]) {
            model.result = @"";
        }
        [resultArr addObject:model];
    }
    return resultArr;
    
}

- (NSArray *)queryAllHistoryModelWithUserId:(NSString *)userId dialogid:(NSString *)dialogid
{
    NSString *sql = @"SELECT * FROM MujiDubHistoryList where userId=? and dialogid=?";
    FMResultSet *rs = [_database executeQuery:sql, userId, dialogid];
    
    NSMutableArray *resultArr = [[NSMutableArray alloc] init];
    while ([rs next]) {
        
        // 查询到一条记录，就应该新建一个Model来放数据
        MujiDubRecordModel *model = [[MujiDubRecordModel alloc] init];
        model.userId = [rs stringForColumn:@"userId"];
        model.dialogid = [rs stringForColumn:@"dialogid"];
        model.dialoglineid = [rs stringForColumn:@"dialoglineid"];
        model.score = [rs stringForColumn:@"score"];
        model.result= [rs stringForColumn:@"result"];
        model.mindex= [rs stringForColumn:@"mindex"];
        
        if (model.score.length == 0 || [model.score containsString:@"null"]) {
            model.score = @"";
        }
        if (model.result.length == 0 || [model.result containsString:@"null"]) {
            model.result = @"";
        }
        [resultArr addObject:model];
    }
    return resultArr;
}
- (NSArray *)queryAllHistoryModelWithUserId:(NSString *)userId dialogid:(NSString *)dialogid dialoglineid:(NSString *)dialoglineid
{
    NSString *sql = @"SELECT * FROM MujiDubHistoryList where userId=? and dialogid=? and dialoglineid=?";
    FMResultSet *rs = [_database executeQuery:sql, userId, dialogid, dialoglineid];
    
    NSMutableArray *resultArr = [[NSMutableArray alloc] init];
    while ([rs next]) {
        
        // 查询到一条记录，就应该新建一个Model来放数据
        MujiDubRecordModel *model = [[MujiDubRecordModel alloc] init];
        model.userId = [rs stringForColumn:@"userId"];
        model.dialogid = [rs stringForColumn:@"dialogid"];
        model.dialoglineid = [rs stringForColumn:@"dialoglineid"];
        model.score = [rs stringForColumn:@"score"];
        model.result= [rs stringForColumn:@"result"];
        model.mindex= [rs stringForColumn:@"mindex"];
        
        if (model.score.length == 0 || [model.score containsString:@"null"]) {
            model.score = @"";
        }
        if (model.result.length == 0 || [model.result containsString:@"null"]) {
            model.result = @"";
        }
        [resultArr addObject:model];
    }
    return resultArr;
}

@end
